package org.example.ams.controller.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.ams.entity.system.SysScheduled;
import org.example.ams.service.system.ISysScheduledService;
import org.example.ams.task.config.SchedulingTask;
import org.example.ams.task.config.TaskRegister;
import org.example.ams.task.taskBean.AbstractTask;
import org.example.ams.util.SpringContextUtils;
import org.example.common.api.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "定时任务接口")
@RestController
@RequestMapping("/scheduled")
public class SysScheduledController {

    @Autowired
    private ISysScheduledService sysScheduledService;
    @Autowired
    private TaskRegister taskRegister;

    /**
     * bean创建后，自动启动状态为1 的定时任务
     */
    @PostConstruct
    public void init() {
        List<SysScheduled> lists =  sysScheduledService.queryBootstrapedTask();
        SchedulingTask task = null;
        if (lists != null && lists.size() > 0) {
            for (SysScheduled item : lists) {
                task = new SchedulingTask(item);
                taskRegister.registerTask(task,item.getCron());
            }
        }
    }

    @ApiOperation("分页查询列表")
    @PreAuthorize("hasAnyAuthority('system:sysscheduled:list','*:*:*')")
    @GetMapping("/list")
    public CommonResult<Map<String,Object>> listByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest request) {
        Map<String, String[]> params = request.getParameterMap();
        Map<String,Object> res = sysScheduledService.queryByPage(currentPage,pageSize,params);
        return CommonResult.success(res,null);
    }

    @PreAuthorize("hasAnyAuthority('system:task:statusupdate','*:*:*')")
    @ApiOperation("启动或停止任务")
    @PostMapping("/stopOrStartTask")
    public CommonResult stopOrStartTask(@RequestParam(required = true) String scheduledId,
                                 @RequestParam(required = true) Integer status )  {
        boolean res = sysScheduledService.updateStatus(scheduledId,status);
        if (res) {
            if (status == 1) {
                // 启动
                SysScheduled sysScheduled = sysScheduledService.queryById(scheduledId);
                if (sysScheduled == null) {
                    return CommonResult.failed();
                }
                SchedulingTask task = new SchedulingTask(sysScheduled);
                taskRegister.registerTask(task,sysScheduled.getCron());
            } else if (status == 0){
                // 停止
                taskRegister.removeTask(scheduledId);
            }
        } else {
            return CommonResult.failed();
        }
        return CommonResult.success(null);
    }

    @PreAuthorize("hasAnyAuthority('system:task:add','*:*:*')")
    @ApiOperation("检查任务是否已经添加过")
    @PostMapping("/checkTaskIsExist")
    public CommonResult checkTaskIsExist(@RequestParam(required = true) String taskId) {
        SysScheduled sysScheduled = sysScheduledService.queryById(taskId);
        // 1 : 已经存在  0: 不存在
        Integer res = 0;
        if (sysScheduled != null) {
            res = 1;
        }
        return CommonResult.success(res,null);
    }


    @PreAuthorize("hasAnyAuthority('system:task:add','*:*:*')")
    @ApiOperation("添加定时任务")
    @PostMapping("/add")
    public CommonResult addTask(@Valid @RequestBody SysScheduled sysScheduled) {
        String cron = sysScheduled.getCron();
        sysScheduled.setCron(cron.substring(0,cron.length() - 1));
        sysScheduledService.addTask(sysScheduled);
        return CommonResult.success(null);
    }



    @PreAuthorize("hasAnyAuthority('system:task:add','*:*:*')")
    @ApiOperation("获取所有未添加的任务")
    @GetMapping("/allTask")
    public CommonResult<List<AbstractTask>> getAllTask() {
        // 1. 获取可以添加的任务
        Map<String,AbstractTask> beans = SpringContextUtils.getBeans(AbstractTask.class);
        Collection<AbstractTask> tasks = beans.values();
        List<AbstractTask> data = tasks.stream().filter(task -> {
            return task.getTasks() != null && task.getTasks().size() > 0;
        }).collect(Collectors.toList());
        return CommonResult.success(data,null);
    }

    @PreAuthorize("hasAnyAuthority('system:task:delete','*:*:*')")
    @ApiOperation("删除任务")
    @DeleteMapping("/delete")
    public CommonResult remove(@RequestParam(required = true) String taskId) {
        // 1. 从数据库中删除任务
        int row = sysScheduledService.remove(taskId);
        if (row == 1) {
            // 2. 停止任务
            taskRegister.removeTask(taskId);
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @PreAuthorize("hasAnyAuthority('system:task:update','*:*:*')")
    @ApiOperation("更新任务")
    @PutMapping("/update")
    public CommonResult update(@RequestBody SysScheduled sysScheduled) {
        boolean flag = sysScheduledService.updateTask(sysScheduled);
        if (!flag) {
            return CommonResult.failed();
        }
        return CommonResult.success(null);
    }
}
